
var webSocket  = null;
var connected  = false;
var checkboard = null;

var selectedCamp = "black";

var regRoomId = /^(.){1,}$/;
var regSize   = /^[1-2][0-9]$/;

function connectServer(id, ip, port, path, camp, size) {
		/*"ws://" + ip + ":" + port + "/Z5CServer_war_exploded/ws/" + id + "/" + camp + "/" + size*/
	webSocket = new WebSocket( // /ws/{roomId}/{connectCamp}/{cbSize}
		"ws://" + ip + ":" + port + "/" + projectRootDir(path) + "/ws/" + encodeURIComponent(id) + "/" + camp + "/" + size);
	
	webSocket.onopen = function() {
		connected = true;
		console.log("connected");
		$(".header").addClass("hid");
		document.getElementById("lblRoom").innerText = decodeURIComponent(id);
		$(".connectTip").removeClass("hid");
		////设定邀请按钮
		$("#btnShare").css("display","block");
		$("#btnShare").click(function() {
			var input = document.getElementById("code");
			input.value = location.protocol + "//" + location.hostname + ":" + location.port + 
				"/" + projectRootDir(location.pathname) + "/go.enter?roomId=" + encodeURIComponent(id);
			input.select();
			document.execCommand("Copy");
			alert("链接已复制到剪贴板，快分享给好友吧！");
		});
	};
	
	webSocket.onmessage = function(data) {
		console.log("dispatching...");
		var response = JSON.parse(data.data);
		console.log(response.type);
		
		switch(response.type) {
			case "go":
				console.log("dispatched to go");
				checkboard.go(response.row, response.col, response.cmp);
				break;
			case "configCheckerboard":
				if(checkboard == null) {
					checkboard = new Checkerboard("checkboard", response.siz, response.cmp);
					if(response.cmp == "black") {
						selectBlack();
					} else {
						selectWhite();
					}
					document.getElementById("txtSize").value = response.siz;
					$("#battleGround").append(checkboard.getEmpty());
				}
				$(".connectTip").addClass("hid");
				////设定撤回按钮
				$("#btnRollback").css("display","block");
				$("#btnRollback").click(function() {
					if(checkboard.getUserConfirmed()) {
						checkboard.requestRollback();
					} else {
						checkboard.setUserConfirmed(true);
						$("#btnRollback").text("撤回棋子");
					}
				});
				break;
			case "getCheckerboard": {
				checkboard = new Checkerboard("checkboard", response.siz, "white");
				document.getElementById("txtSize").value = response.siz;
				$("#battleGround").append(checkboard.getEmpty());
				for(ijc of response.data) {
					checkboard.go(ijc[0], ijc[1], value2Camp(ijc[2]));
				}
				$(".connectTip").addClass("hid");
				break;
			}
			case "rollback":
				console.log("dispatched to Rollback: " + response.rbk);
				checkboard.rollback(response.rbk[0], response.rbk[1], response.rbk[2], response.rbk[3]);
				break;
			case "clean": 
				checkboard.clean();
				break;
			case "blackWin": {
				console.log("winBy: " + response.win);
				checkboard.go(response.row, response.col, response.cmp);
				checkboard.showWinBy(response.win);
				checkboard.setUserConfirmed(false);
				$("#btnRollback").text("战果确认");
				alert("Black Win !");
				//checkboard.clean();
				break;
			}
			case "whiteWin": 
				console.log("winBy: " + response.win);
				checkboard.go(response.row, response.col, response.cmp);
				checkboard.showWinBy(response.win);
				checkboard.setUserConfirmed(false);
				$("#btnRollback").text("战果确认");
				alert("White Win !");
				//checkboard.clean();
				break;
			case "draw": 
				alert("Draw !");
				checkboard.setUserConfirmed(false);
				//checkboard.clean();
				break;
			case "exit": 
				checkboard.clean();
				break;
		}
	};
	
	webSocket.onclose = function() {
		webSocket.close();
		connected = false;
	};
}

function selectBlack() {
	console.log("select black");
	$("#btnBlack").removeClass("black");
	$("#btnBlack").addClass("selectedButton");
	$("#btnWhite").removeClass("selectedButton");
	$("#btnWhite").addClass("white");
	
	selectedCamp = "black";
}

function selectWhite() {
	console.log("select white");
	$("#btnWhite").removeClass("white");
	$("#btnWhite").addClass("selectedButton");
	$("#btnBlack").removeClass("selectedButton");
	$("#btnBlack").addClass("black");
	
	selectedCamp = "white";
}

function initHeader() {
	$("#btnBlack").click(selectBlack);
	$("#btnWhite").click(selectWhite);
	$("#btnConnect").click(function(){

		if(!regRoomId.test(document.getElementById("txtRoom").value.toString())) {
			alert("请输入对局房间号");
			return;
		}

		if(!regSize.test(document.getElementById("txtSize").value.toString())) {
			alert("请输入正确的棋盘尺寸(10~29)");
			return;
		}

		console.log("connecting..");
		connectServer(
			encodeURIComponent(document.getElementById("txtRoom").value), 
			location.hostname, 
			location.port,
			location.pathname,
			selectedCamp, 
			document.getElementById("txtSize").value
		);
	});
}

$(document).ready(function() {
	/*
	// for test
	checkboard = new Checkerboard("0", 15, "white");
	$("#battleGround").append(checkboard.getEmpty());
	$("#btnRollback").css("display","block");
	$("#btnShare").css("display","block");
	*/
	
	autologin();
	
	connected = false;
	selectBlack();

	$("#btnLogin").click(function() {
		location.href = "login.html";
	});
	
	$.ajax({
		url: "get.enter",
		type:"GET",
		dataType:"json",
		success:function (response) {
			//console.log(data);
			switch(response.type) {
				case "getRoomId":
					connectServer(response.roomId, location.hostname, location.port, location.pathname, response.hostCamp, response.size);
					break;
				case "roomIdNotFound":
				default:
					initHeader();
					break;
			}
		}
	});
});

function Checkerboard(cbid, size, camp) {
	/*camp: "white" or "black" */
	this.cbid = cbid;
	this.size = size;
	this.camp = camp;
	this.ground = null;
	this.userConfirmedBattleResult = true;
	
	this.rollbackReq = JSON.stringify({
		type:"requestRollback",
		cmp:this.camp
	});

	this.confirmReq = JSON.stringify({
		type:"playerReady"
	});

	this.requestGo = function(i, j) {
		if(!connected  ||  !this.userConfirmedBattleResult) return;
		var msg = JSON.stringify({
			type:"requestGo",
			row:i,
			col:j,
			cmp:this.camp
		});
		webSocket.send(msg);
	};
	
	this.sendConfirmed = function() {
		if(!connected) return;
		webSocket.send(this.confirmReq);
	};

	this.setUserConfirmed = function(confirmed) {
		this.userConfirmedBattleResult = confirmed;
		if(confirmed) {
			this.sendConfirmed();
			this.clean();
		}
	};

	this.getUserConfirmed = function() {
		return this.userConfirmedBattleResult;
	};
	
	this.removeTip = function() {
		$(".pTip").removeClass("pTip");
		//$(".showTip").removeClass("showTip");
	};

	this.tip = function(i, j) {
		$("#pieceTip_" + i + "_" + j).addClass("pTip");
		//$("#piece_" + i + "_" + j).addClass("showTip");
	};
	
	this.updateTip = function(i, j) {
		this.removeTip();
		this.tip(i, j);
	};

	this.go = function(i, j, theCamp) {
		console.log("go " + i + "," + j + " : " + theCamp);

		var ijStr = i + "_" + j;
		
		$("#" + "piece_" + ijStr).addClass("isDown");

		/*
		if(this.prei != -1  &&  this.prej != -1)
			$("#pieceTip_" + this.prei + "_" + this.prej).removeClass("pTip");
		*/
		this.updateTip(i, j);
		
		var pInner = $("#" + "pieceInner_" + ijStr);
		pInner.removeClass("black");
		pInner.removeClass("white");
		pInner.addClass(theCamp);
		pInner.addClass("innerDown");
	};

	this.showWinBy = function (winBy) {
		for(ij of winBy) {
			this.tip(ij[0], ij[1]);
		}
	};
	
	this.remove = function(i, j) {
		var pInner = $("#pieceInner_" + i + "_" + j);
		$("#piece_" + i + "_" + j).removeClass("isDown");
		$("#pieceTip_" + i + "_" + j).removeClass("pTip");
		pInner.removeClass("innerDown");
		pInner.removeClass("white");
		pInner.removeClass("black");
		pInner.addClass(this.camp);
	};

	this.requestRollback = function() {
		console.log("requestRollback: " + this.rollbackReq);
		webSocket.send(this.rollbackReq);
	};
	
	this.rollback = function(i, j, ii, jj) {
		console.log("doRollback");
		this.remove(i, j);
		if(ii != -1 && jj != -1) {
			this.tip(ii, jj);
		}
	};
	
	this.setCamp = function(theCamp) {
		this.camp = theCamp;
	};

	this.clean = function() {
		for(var i = 0; i < this.size; ++i) {
			for(var j = 0; j < this.size; ++j) {
				this.remove(i, j);
			}
		}
	};
	
	this.getEmpty = function() {
		var ckboard = $("<div id=\"checkerboard_" + this.cbid + "\" class=\"checkerboard\">");
		
		var echHr = null;
		for(var i = 0; i < this.size; ++i) {
			echHr = $("<div class=\"btgHr\">");
			for(var j = 0; j < this.size; ++j) {
				if(i == j && i == ((this.size) >> 1)) {
					echHr.append($("<div class=\"btgVr\"><div class=\"centerPoint\"></div><div id=\"piece_" + i + "_" + j + 
							   "\" class=\"pieces\" onclick=\"" + this.cbid + ".requestGo(" + i + "," + j + ",'" + this.camp + "'" +
							   ")\"><div id=\"pieceInner_" + i + "_" + j + "\" class=\"pieceInner " + this.camp + "\"><div id=\"pieceTip_" + i + "_" + j + "\" class=\"pieceTip\"></div></div></div></div>"));
				} else {
					echHr.append($("<div class=\"btgVr\"><div id=\"piece_" + i + "_" + j + 
							   "\" class=\"pieces\" onclick=\"" + this.cbid + ".requestGo(" + i + "," + j + ",'" + this.camp + "'" +
							   ")\"><div id=\"pieceInner_" + i + "_" + j + "\" class=\"pieceInner " + this.camp + "\"><div id=\"pieceTip_" + i + "_" + j + "\" class=\"pieceTip\"></div></div></div></div>"));
				}
			}
			echHr.append($("<div class=\"btgVr\"></div>"));
			
			ckboard.append(echHr);
		}
	
		echHr = $("<div class=\"btgHr\">");
		for(var j = 0; j <= this.size; ++j) {
			echHr.append($("<div class=\"btgVr\"></div>"));
		}
		
		ckboard.append(echHr);
		this.ground = ckboard;
		return ckboard;
	};
}
